package chances.epg.api.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import chances.epg.api.controller.model.ResultResponse;
import chances.epg.api.controller.model.ResultSetResponse;
import chances.epg.commons.log.EpgLogFactory;
import chances.epg.commons.utils.RequestUtils;
import chances.epg.data.PageBean;
import chances.epg.data.model.CategoryItemProxy;
import chances.epg.data.service.CategoryItemProxyService;
import chances.epg.data.service.ContentService;
import chances.epg.data.service.EpgUpdateService;
import chances.epg.entity.content.Category;
import chances.epg.entity.content.CategoryItem;

@RestController
public class CategoryDataController extends AbstractDataController {
	private static Logger logger = EpgLogFactory.getSystemLogger();

	@Autowired
	private ContentService contentService;
	
	@Autowired
	private CategoryItemProxyService ciProxyService;
	
	@Autowired
	private  EpgUpdateService epgUpdateService;

	@RequestMapping(value = "/category/{categoryCode}")
	public ResultResponse<Category> getCategory(@PathVariable String categoryCode, ModelMap model,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		Category category = null;
		int result = SUCCESS;

		try {
			category = contentService.getCategoryByCode(categoryCode);
			if (category == null) {
				result = OBJ_NOT_FOUND;
			}

		} catch (DataAccessException ex) {
			result = DB_ERROR;
			logger.error(ex.getMessage(), ex);
		} catch (Throwable ex) {
			result = ERROR;
			logger.error(ex.getMessage(), ex);
		}

		return new ResultResponse<Category>(result, category);
	}

	@RequestMapping(value = "/categorylist/{categoryCode}")
	public ResultResponse<List<Category>> getCategoryList(@PathVariable String categoryCode, ModelMap model,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Category> categorys = null;
		int result = SUCCESS;

		try {
			categorys = contentService.getCategoryLists(categoryCode);
		} catch (DataAccessException ex) {
			result = DB_ERROR;
			logger.error(ex.getMessage(), ex);
		} catch (Throwable ex) {
			result = ERROR;
			logger.error(ex.getMessage(), ex);
		}
		return new ResultResponse<List<Category>>(result, categorys);

	}

	@RequestMapping(value = "/contentlist/{categoryCode}")
	public ResultSetResponse<CategoryItem> getContentList(@PathVariable String categoryCode, ModelMap model,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		String itemType = RequestUtils.getParameter(request, "itemtype", "");
		int size = RequestUtils.getParameter(request, "size", DEFAULT_SIZE);
		int pageIndex = RequestUtils.getParameter(request, "pageindex", 1);
		PageBean pageBean = this.createPageBean(size, pageIndex);
		List<CategoryItem> items = null;
		int result = SUCCESS;
		try {
			this.categoryService.listCategoryItem(categoryCode, itemType, 0, pageBean);
			this.contentService.listCateoryContent(items);
		} catch (DataAccessException ex) {
			result = DB_ERROR;
			logger.error(ex.getMessage(), ex);
		} catch (Throwable ex) {
			result = ERROR;
			logger.error(ex.getMessage(), ex);
		}
		return new ResultSetResponse<>(result, items, pageBean);
	}

	@RequestMapping(value = "/categoryitem/{categoryCode}")
	public ResultSetResponse<CategoryItem> getCategoryItems(@PathVariable String categoryCode, ModelMap model,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		String itemType = RequestUtils.getParameter(request, "itemtype", "");
		String random = RequestUtils.getParameter(request, "random", "false");
		boolean byParent = RequestUtils.getParameter(request, "byparent", false);

		int size = RequestUtils.getParameter(request, "size", DEFAULT_SIZE);
		int pageIndex = RequestUtils.getParameter(request, "pageindex", 1);

		int result = SUCCESS;
		PageBean pageBean = null;
		List<CategoryItem> categoryItems = null;

		try {
			if ("true".equals(random)) {
				categoryItems = this.categoryService.queryRandomItem(categoryCode, itemType, size, byParent);
			} else {
				pageBean = this.createPageBean(size, pageIndex);
				categoryItems = this.categoryService.listCategoryItem(categoryCode, itemType, 0, pageBean);
			}
			this.setResultUrl(categoryItems, request);
		} catch (DataAccessException ex) {
			result = DB_ERROR;
			logger.error(ex.getMessage(), ex);
		} catch (Throwable ex) {
			result = ERROR;
			logger.error(ex.getMessage(), ex);
		}
		return new ResultSetResponse<>(result, categoryItems, pageBean);

	}
	
	@RequestMapping(value = "/categoryItemProxy/{itemType}/{categoryCode}")
	public ResultSetResponse<CategoryItemProxy> listCategoryItem(@PathVariable String itemType, @PathVariable String categoryCode,
			ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String random = RequestUtils.getParameter(request, "random", "false");
		boolean byParent = RequestUtils.getParameter(request, "byparent", false);
		int size = RequestUtils.getParameter(request, "size", DEFAULT_SIZE);
		int pageIndex = RequestUtils.getParameter(request, "pageindex", 1);
		PageBean pageBean = this.createPageBean(size, pageIndex);
		int start = RequestUtils.getParameter(request, "start", 0);
		int result = SUCCESS;
		List<CategoryItemProxy> ciProxys = null;
		try {
			List<CategoryItem> items = null;
			if ("true".equals(random)) {
				items = this.categoryService.queryRandomItem(categoryCode, itemType, size, byParent);
			} else {
				pageBean = this.createPageBean(size, pageIndex);
				items = this.categoryService.listCategoryItem(categoryCode, itemType, start, pageBean);
			}
			setResultUrl(items, request);
			ciProxys = ciProxyService.listCategoryItem(items, categoryCode, itemType, start, pageBean);
		} catch (Exception e) {
			result = ERROR;
		}
		return new ResultSetResponse<>(result, ciProxys, pageBean);
	}
	
	@RequestMapping(value = "/categoryCount")
	public ResultResponse<Map<String, Integer>> categoryCount(
			ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String codes = RequestUtils.getParameter(request, "categorys", "");
		int result = SUCCESS;
		Map<String, Integer> countMap = new HashMap<String, Integer>();
		if(StringUtils.isNotEmpty(codes)) {
			String[] codeArray = codes.split(",");
			epgUpdateService.queryCategoryCount();
			countMap = epgUpdateService.getCategoryCount(codeArray);
		} else {
			result = ERROR;
		}
		return new ResultResponse<Map<String, Integer>>(result, countMap);
	}

}
